import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { getUserInfoAPI } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户登录的token
    token: '',
    // 用户信息对象
    userInfoObj: {}
  },
  mutations: {
    // 更新token
    updateToken(state, value) {
      state.token = value
    },
    // 更新用户信息
    upDateUserInfo(state, value) {
      state.userInfoObj = value
    }
  },
  actions: {
    // 获取用户资料（实时更新用户信息）
    async getUserInfo(store) {
      const {
        data: { data }
      } = await getUserInfoAPI()
      store.commit('upDateUserInfo', data)
    }
  },
  getters: {
    username: (state) => state.userInfoObj.username,
    user_pic: (state) => state.userInfoObj.user_pic,
    nickname: (state) => state.userInfoObj.nickname
  },
  modules: {},
  plugins: [createPersistedState()]
})
